import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';
// export const baseUrl = 'http://47.115.225.31:8011/blow';
export const baseUrl = 'https://wsh.swpu.edu.cn/blow_api';
export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}
// axios.defaults.baseURL = "https://accommodation-booking-api.sicnu.edu.cn/activity"
axios.defaults.baseURL = baseUrl;
// if (import.meta.env.VITE_API_BASE_URL) {
//   axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
// }

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    //我不知道那个后端为什么要将成功的返回设置为0
    if (res.code == 0) {
      return res;
    }
    if (res.code !== 200) {
      Message.error({
        content: res.msg || 'Error',
        duration: 5 * 1000,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [50008, 50012, 50014].includes(res.code) &&
        response.config.url !== '/api/user/info'
      ) {
        Modal.error({
          title: 'Confirm logout',
          content:
            'You have been logged out, you can cancel to stay on this page, or log in again',
          okText: 'Re-Login',
          async onOk() {
            const userStore = useUserStore();

            await userStore.logout();
            window.location.reload();
          },
        });
      }
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    return res;
  },
  (error) => {
    Message.error({
      content: error.msg || 'Request Error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

// axios.interceptors.response.use(
//   (response: AxiosResponse) => {
//     // 处理二进制响应类型（如Excel导出）
//     if (response.config.responseType === 'blob') {
//       return response; // 返回完整响应对象，包含headers等信息
//     }

//     // 处理标准JSON响应
//     const res = response.data as HttpResponse;

//     if (res.code !== 200) {
//       Message.error({
//         content: res.msg || 'Error',
//         duration: 5 * 1000,
//       });

//       // 处理Token失效的特殊情况
//       if (
//         [50008, 50012, 50014].includes(res.code) &&
//         response.config.url !== '/api/user/info'
//       ) {
//         Modal.error({
//           title: '确认退出登录',
//           content: '您的登录状态已失效，请重新登录',
//           okText: '重新登录',
//           async onOk() {
//             const userStore = useUserStore();
//             await userStore.logout();
//             window.location.reload();
//           },
//         });
//       }
//       return Promise.reject(new Error(res.msg || 'Error'));
//     }
//     return res;
//   },
//   (error) => {
//     // 处理二进制响应错误
//     if (error.config?.responseType === 'blob' && error.response?.data instanceof Blob) {
//       return new Promise((resolve, reject) => {
//         const reader = new FileReader();
//         reader.onload = () => {
//           try {
//             // 尝试解析错误信息
//             const errorData = JSON.parse(reader.result as string);
//             Message.error({
//               content: errorData.msg || '导出失败',
//               duration: 5 * 1000,
//             });
//           } catch (e) {
//             // 无法解析的错误响应
//             Message.error({
//               content: '导出失败，文件格式错误',
//               duration: 5 * 1000,
//             });
//           }
//           reject(error);
//         };
//         reader.readAsText(error.response.data);
//       });
//     }

//     // 处理标准错误响应
//     const errorMessage = error.response?.data?.msg || error.message || '请求错误';
//     Message.error({
//       content: errorMessage,
//       duration: 5 * 1000,
//     });
//     return Promise.reject(error);
//   }
// );
